<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Document } from '@element-plus/icons-vue'
import { postFeatureEngineering } from '@/api/product/machineLearning.js'

const props = defineProps({
	modelValue: {
		type: Object,
		default: () => ({}),
	},
})

const emit = defineEmits(['update:modelValue', 'verification'])

// 特征列全选状态
const featureSelectAll = ref(false)

// 添加图片相关状态
const isLoadingChart = ref(false)
const hasChart = ref(props.modelValue.imageData !== '')

// 特征列全选计算属性
const isFeatureAllSelected = computed(() => {
	return (
		props.modelValue.targetFeatureTable.length > 0 &&
		props.modelValue.targetFeatureTable.every((item) => item.isFeature)
	)
})

// 计算唯一被选中的目标列索引
const selectedTargetIndex = computed(() => {
	return props.modelValue.targetFeatureTable.findIndex((item) => item.isTarget)
})

// 特征列全选处理
const handleFeatureSelectAll = (val) => {
	props.modelValue.targetFeatureTable.forEach((item) => {
		if (!item.isTarget) {
			item.isFeature = val
		}
	})
	handleTargetSelect()
}

// 目标列选择处理（只允许单选）
const handleTargetSelect = async () => {
	if (
		props.modelValue.targetFeatureTable.filter(
			(item) => item.isFeature === true
		).length < 2
	) {
		// 如果取消选择目标列，清空图表
		props.modelValue.imageData = ''
		hasChart.value = false
		return
	}
	try {
		isLoadingChart.value = true
		hasChart.value = false

		const res = await postFeatureEngineering({
			file_name: props.modelValue.fileName,
			target: props.modelValue.targetFeatureTable
				.filter((item) => item.isFeature === true)
				.map((item) => item.name),
			method: 'pearson',
		})

		if (res.code === 200 && res.data.code === 200) {
			console.log('Feature engineering result:', res.data.data)
			// 将base64字符串转换为图片
			props.modelValue.imageData = `data:image/png;base64,${res.data.data}`
			hasChart.value = true
		} else {
			ElMessage.error('生成特征工程图表失败')
		}
	} catch (error) {
		console.error('Feature engineering error:', error)
		ElMessage.error('生成特征工程图表失败')
	} finally {
		isLoadingChart.value = false
	}
}

const verification = async () => {
	try {
		const hasFeature = props.modelValue.targetFeatureTable.some(
			(item) => item.isFeature
		)
		const hasTarget = props.modelValue.targetFeatureTable.some(
			(item) => item.isTarget
		)
		if (hasFeature === false || hasTarget === false) {
			if (hasFeature === false) {
				ElMessage.error('请至少勾选一个特征列')
				return false
			}
			if (hasTarget === false) {
				ElMessage.error('请至少勾选一个目标列')
				return false
			}
		}

		return true
	} catch (e) {
		return false
	}
}

defineExpose({
	verification,
})

onMounted(() => {})
</script>

<template>
	<div class="component TargetFeatureColumn">
		<div class="component-header">
			<div class="component-header-title">
				目标特征列设置
				<span class="component-header-title-desc">
					已选择有空值的字段，系统会自动对有空值的字段进行默认缺失值处理，如需要更改缺失值处理方法，请添加分类-缺失值处理步骤
				</span>
			</div>
		</div>

		<div class="TargetFeatureColumn-content">
			<el-table
				:data="props.modelValue.targetFeatureTable"
				border
				class="TargetFeatureColumn-content-table"
			>
				<el-table-column prop="name" label="可用字段">
					<template #default="{ row }">
						<div class="field-item">
							<div class="field-icon">123</div>
							<span>{{ row.name }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="特征列" width="120">
					<template #header>
						<div style="display: flex; align-items: center">
							<el-checkbox
								v-model="featureSelectAll"
								:indeterminate="
									!isFeatureAllSelected &&
									props.modelValue.targetFeatureTable.some(
										(item) => item.isFeature
									)
								"
								@change="handleFeatureSelectAll"
							/>
							<span style="margin-left: 8px">特征列</span>
						</div>
					</template>
					<template #default="{ row, $index }">
						<el-checkbox
							v-model="row.isFeature"
							:disabled="row.isTarget"
							@change="() => handleTargetSelect(row, $index)"
						/>
					</template>
				</el-table-column>
				<el-table-column label="目标列" width="120">
					<template #header>
						<span>目标列</span>
					</template>
					<template #default="{ row, $index }">
						<el-checkbox
							v-model="row.isTarget"
							:disabled="
								(selectedTargetIndex !== -1 &&
									selectedTargetIndex !== $index) ||
								row.isFeature ||
								row.name === 'phase'
							"
						/>
					</template>
				</el-table-column>
			</el-table>

			<div class="TargetFeatureColumn-content-view">
				<div v-if="isLoadingChart" class="chart-state loading-chart">
					<el-icon class="loading-icon"><Loading /></el-icon>
					<span>正在生成特征工程图表...</span>
				</div>
				<div v-else-if="hasChart" class="chart-state chart-display">
					<div class="chart-header">
						<h4>特征工程相关性分析</h4>
					</div>
					<div class="chart-image-container">
						<img
							:src="props.modelValue.imageData"
							alt="Feature Engineering Chart"
							@load="() => console.log('Chart image loaded')"
							@error="() => console.log('Chart image load error')"
						/>
					</div>
				</div>
				<div v-else class="chart-state no-chart-message">
					<el-icon class="empty-icon"><Document /></el-icon>
					<span>请选择目标列生成特征工程图表</span>
					<p class="empty-desc">
						选择目标列后，系统会自动生成特征与目标的相关性分析图表
					</p>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped lang="scss">
@import url('./index.scss');

.TargetFeatureColumn {
	&-content {
		padding: 20px;
		background-color: #fff;
		display: flex;
		gap: 20px;
		min-height: 500px;

		&-table {
			flex: 1;
			min-width: 400px;
		}

		&-view {
			flex: 2;
			min-width: 300px;
			border: 1px solid #ebeef5;
			border-radius: 4px;
			background-color: #f9fafc;
			display: flex;
			flex-direction: column;
		}
	}
}

.field-item {
	display: flex;
	align-items: center;
	gap: 8px;

	.field-icon {
		width: 24px;
		height: 16px;
		background-color: #20b2aa;
		color: white;
		border-radius: 4px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
		font-weight: bold;
	}
}

.chart-state {
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20px;
}

.loading-chart {
	color: #606266;

	.loading-icon {
		font-size: 24px;
		margin-bottom: 10px;
		animation: rotate 2s linear infinite;
	}

	span {
		font-size: 14px;
	}
}

.chart-display {
	height: 100%;

	.chart-header {
		margin-bottom: 15px;
		text-align: center;

		h4 {
			margin: 0;
			color: #303133;
			font-size: 16px;
			font-weight: 500;
		}
	}

	.chart-image-container {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		background-color: #fff;
		border-radius: 4px;
		border: 1px solid #ebeef5;
		overflow: hidden;
		padding: 20px;

		img {
			max-width: 100%;
			max-height: 100%;
			object-fit: contain;
			transition: transform 0.3s ease;
			border-radius: 4px;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

			&:hover {
				transform: scale(1.02);
			}
		}
	}
}

.no-chart-message {
	color: #909399;
	text-align: center;

	.empty-icon {
		font-size: 48px;
		margin-bottom: 15px;
		color: #c0c4cc;
	}

	span {
		font-size: 16px;
		font-weight: 500;
		color: #606266;
		margin-bottom: 8px;
		display: block;
	}

	.empty-desc {
		font-size: 14px;
		color: #909399;
		margin: 0;
		line-height: 1.5;
	}
}

@keyframes rotate {
	from {
		transform: rotate(0deg);
	}
	to {
		transform: rotate(360deg);
	}
}
</style>
